package top.blackcat.learn.shiro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.blackcat.learn.shiro.entity.SysUser;
import top.blackcat.learn.shiro.exception.ExceptionRes.ApiError;
import top.blackcat.learn.shiro.exception.ServiceException;
import top.blackcat.learn.shiro.mapper.SysUserMapper;
import top.blackcat.learn.shiro.service.LoginService;

import java.util.Date;
import java.util.List;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser findByName(String username) throws ServiceException {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        queryWrapper.orderByDesc("create_time");
        List<SysUser> users = sysUserMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(users)) {
            throw new ServiceException(ApiError.ERROR_10010001);
        }
        return users.get(0);
    }

    @Override
    public String addUser(String username, String password) throws ServiceException {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        List list=sysUserMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(list)){
           throw  new ServiceException(ApiError.ERROR_10010003);
        }



        SysUser user = new SysUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setCreateTime(new Date());
        return sysUserMapper.insert(user)+"";
    }


}
